package com.gistone.commis.api.restController;

import com.gistone.commis.constant.Status;
import com.gistone.commis.database.GetBySqlMapper;
import com.gistone.commis.dto.*;
import com.gistone.commis.entity.*;
import com.gistone.commis.mapper.CommunityMapper;
import com.gistone.commis.mapper.DepartMapper;
import com.gistone.commis.mapper.PublicFundChangeMapper;
import com.gistone.commis.mapper.PublicFundMapper;
import com.gistone.commis.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import freemarker.template.Template;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLConnection;
import java.util.*;

/**
 * Created by wangfan on 2017/5/20.
 */
@RestController("apiPublicFundController")
@RequestMapping("api/publicFund")
public class PublicFundController {

	private static final Logger logger = LoggerFactory.getLogger(PublicFundController.class);
	@Autowired
	private GetBySqlMapper getBySqlMapper;

	@Autowired
	private PublicFundMapper publicFundMapper;


	@Autowired
	private PublicFundChangeMapper publicFundChangeMapper;

	@Value("${app.uploadPath}")
	private String path;

	@Autowired
	private CommunityMapper communityMapper;

	@Autowired
	private DepartMapper departMapper;

	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = "/muticreate")
	public Result muticreate(HttpServletRequest request, HttpServletResponse response, PublicFund publicFund ) {
		Date date= new Date();
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		publicFund.setUserId(user.getUserId());
		publicFund.setPersonName(user.getRealName());
		publicFund.setRegisterTime(date);


		try {
			if (null == publicFund.getCommunityId()) {
				publicFund.setCommunityId(user.getCommunity().getCommunityId());
				publicFund.setCommunityName(user.getCommunity().getCommunityName());
			}
			publicFund.setIsOff(0);
			publicFund.setSubmitNumber(1);
			if (null == publicFund.getDepartId()) {
				publicFund.setDepartId(1);
			}

			File file =new File(publicFund.getAttachpath1());
			if(!file.exists()){
				return new Result(Status.ERROR,"基层党组织服务群众经费使用请示对应文件未上传，请先点击上传按钮进行上传","");
			}
			file =new File(publicFund.getAttachpath2());
			if(!file.exists()){
				return new Result(Status.ERROR,"八里庄街道基层党组织服务群众项目计划书对应文件未上传，请先点击上传按钮进行上传","");
			}
			file =new File(publicFund.getAttachpath3());
			if(!file.exists()){
				return new Result(Status.ERROR,"服务群众经费使用初步计划表对应文件未上传，请先点击上传按钮进行上传","");
			}

			if (publicFundMapper.insertSelective(publicFund) > 0) {


				PublicFundChange publicFundChange = new PublicFundChange();
				publicFundChange.setPfId(publicFund.getPfId());
				publicFundChange.setCurrentState(AuditState.WATING);
				publicFundChange.setCurrentAuditorId(user.getUserId());
				publicFundChange.setLastAuditorId(user.getUserId());
				publicFundChange.setCurrentDatetime(date);
				publicFundChange.setLastDatetime(date);
				publicFundChange.setSubmitNumber(publicFund.getSubmitNumber());
				publicFundChange.setIsValid(false);


				if (publicFundChangeMapper.insert(publicFundChange) > 0) {
					logger.info("保存群众经费信息成功");
				} else {
					logger.info("保存群众经费信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}
			} else {
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			}
		} catch (NumberFormatException e) {
			return new Result(Status.ERROR,"发生错误，请检查是否填写正确","");
		}


		return new Result("成功");

	}

	@RequestMapping("/btDownload")
	public void btDownload(@RequestParam String filepath1,@RequestParam String filepath2,@RequestParam String filepath3, HttpServletRequest request, HttpServletResponse response) throws Exception {

		List<File> files = new ArrayList<File>();
		files.add(new File(filepath1));
		files.add(new File(filepath2));
		files.add(new File(filepath3));
		String tmpFileName = "群众经费"+System.currentTimeMillis()+".zip";
		ZipUtil.downLoadFiles(files,tmpFileName,response);
	}

	@RequestMapping("/download")
	public void download(@RequestParam String filepath, HttpServletRequest request, HttpServletResponse response) throws Exception {

		System.out.println("------"+filepath);
		File file = new File(filepath);
		if  (!file .exists()  && !file .isDirectory())
		{
			return;
		}


		// 下载文件的默认名称
		String filename = file.getName();
		System.out.println("------"+filename);
		ResponseHeaderUtil.setResponseHeader(response, filename);
		response.setContentLength((int) file.length());
		InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
		FileCopyUtils.copy(inputStream, response.getOutputStream());




	}


	/**
	 * 根据id获取群众经费信息
	 * @param id
	 * @return
	 */

	@RequestMapping(method = RequestMethod.GET, value = "/{id}")
	public PublicFund publicFund(@PathVariable int id) {
		PublicFund publicFund =publicFundMapper.selectByPrimaryKey(id);
		return publicFund;
	}
	/**
	 * 新建群众经费信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@Transactional
	@RequestMapping(method = RequestMethod.POST, value = "/create")
	public EditorResult<PublicFund> create(HttpServletRequest request, HttpServletResponse response) {
		PublicFund publicFund = new PublicFund();
		Date date= new Date();
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		publicFund.setUserId(user.getUserId());
		publicFund.setPersonName(user.getRealName());
		publicFund.setRegisterTime(date);
		EditorResult<PublicFund> publicFundEditorResult = new EditorResult<>();
		List<FieldError> fieldErrorList = new ArrayList<>();
		getPublicFund (request, "data[0][", publicFund,fieldErrorList);
		if(null==publicFund.getCommunityId()){
			publicFund.setCommunityId(user.getCommunity().getCommunityId());
		}
		publicFund.setIsOff(0);
		if(null==publicFund.getDepartId()){
			publicFund.setDepartId(1);
		}



        if(fieldErrorList.size()>0){
			logger.error("字段格式错误");
            publicFundEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return publicFundEditorResult;
        }
		if (publicFundMapper.insertSelective(publicFund) > 0) {
			List<PublicFund> data = new ArrayList<>();
			data.add(publicFundMapper.selectByPrimaryKey(publicFund.getPfId()))	;
			publicFundEditorResult.setData(data);

			PublicFundChange publicFundChange = new PublicFundChange();
			publicFundChange.setPfId(publicFund.getPfId());
			publicFundChange.setCurrentState(AuditState.WATING);
			publicFundChange.setCurrentDatetime(date);
			publicFundChange.setCurrentAuditorId(user.getUserId());
			publicFundChange.setLastAuditorId(user.getUserId());
			publicFundChange.setLastDatetime(date);
			publicFundChange.setSubmitNumber(publicFund.getSubmitNumber());

			publicFundChange.setIsValid(false);


			if(publicFundChangeMapper.insert(publicFundChange)>0){
				logger.info("保存群众经费信息成功");
			}else{
				logger.info("保存群众经费信息失败");
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

			}
		} else {
			response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
		}


		return publicFundEditorResult;

	}

	/**
	 * 批量修改群众经费信息， id以,号分割
	 *
	 * @param houseIdStr
	 * @param request
	 * @return
	 */

	@Transactional
	@RequestMapping(method = RequestMethod.PUT, value = "/edit")
	public Object edit(@RequestParam("id") String houseIdStr, HttpServletRequest request, HttpServletResponse response) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		String[] arr = houseIdStr.split(",");
		EditorResult<PublicFund> publicFundEditorResult = new EditorResult<>();
		List<PublicFund> data =new ArrayList<>();
		for (int i = 0; i < arr.length; i++) {
			int publicFundId = Integer.valueOf(arr[i]);
			PublicFund publicFund = new PublicFund();
			publicFund.setPfId(publicFundId);
			List<FieldError> fieldErrorList = new ArrayList<>();
			publicFund.setUserId(user.getUserId());
			getPublicFund(request, "data[" + publicFundId + "][", publicFund, fieldErrorList );
			if(fieldErrorList.size()>0){
				logger.error("字段错误");
				publicFundEditorResult.setFieldErrors(fieldErrorList);
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return publicFundEditorResult;
			}
			PublicFund f = publicFundMapper.selectByPrimaryKey(publicFundId);
			int lastSubmitNO=f.getSubmitNumber();
			int currentSubmitNO =publicFund.getSubmitNumber();
			if (publicFundMapper.updateByPrimaryKeySelective(publicFund) > 0) {
				f = publicFundMapper.selectByPrimaryKey(publicFundId);
				data.add(f);
				PublicFundChange publicFundChange ;
				if(f.getIsDelete()==0) {
					if (lastSubmitNO == currentSubmitNO && user.getUserTypeId() == 1) {//更改信息
						publicFundChange = new PublicFundChange();
						publicFundChange.setPfId(f.getPfId());
						publicFundChange.setCurrentState(AuditState.Edit);
						publicFundChange.setCurrentAuditorId(user.getUserId());
						publicFundChange.setLastAuditorId(user.getUserId());
						publicFundChange.setCurrentDatetime(new Date());
						publicFundChange.setSubmitNumber(publicFund.getSubmitNumber());

						publicFundChange.setIsValid(true);
					} else {//重新提交
						publicFundChange = new PublicFundChange();
						publicFundChange.setPfId(f.getPfId());
						publicFundChange.setCurrentState(AuditState.RESUBMIT);
						publicFundChange.setCurrentAuditorId(user.getUserId());
						publicFundChange.setLastAuditorId(user.getUserId());
						publicFundChange.setCurrentDatetime(new Date());
						publicFundChange.setSubmitNumber(publicFund.getSubmitNumber());

						publicFundChange.setIsValid(false);
					}
				}else{

					publicFundChange = new PublicFundChange();
					publicFundChange.setPfId(f.getPfId());
					publicFundChange.setCurrentState(AuditState.DELETE);
					publicFundChange.setCurrentAuditorId(user.getUserId());
					publicFundChange.setLastAuditorId(user.getUserId());
					publicFundChange.setCurrentDatetime(new Date());
					publicFundChange.setSubmitNumber(publicFund.getSubmitNumber());

					publicFundChange.setIsValid(true);

				}



				if(publicFundChangeMapper.insert(publicFundChange)>0){
					logger.info("保存群众经费日志信息成功");
				}else{
					logger.info("保存群众经费日志信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}



			}else{
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			}


		}
		publicFundEditorResult.setData(data);
		return publicFundEditorResult;


	}


	/**
	 * 群众经费删除
	 * 通过群众经费ID批量删除房屋信息， id以,号分割
	 *
	 * @param publicFundIdStr
	 * @param response
	 * @return
	 */
	@Transactional
	@RequestMapping(method = RequestMethod.DELETE, value = "/remove")
	public Object remove(@RequestParam("id") String publicFundIdStr, HttpServletResponse response) {
		String[] arr = publicFundIdStr.split(",");
		EditorResult<PublicFund> publicFundEditorResult = new EditorResult<>();
		for (int i = 0; i < arr.length; i++) {
			int publicFundId = Integer.valueOf(arr[i]);
			PublicFund publicFund =new PublicFund();
			publicFund.setIsDelete(1);
			publicFund.setPfId(publicFundId);
			if (publicFundMapper.updateByPrimaryKeySelective(publicFund) > 0) {
				System.out.println("删除" + publicFundId + "成功！");


			} else {
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			}
		}
		return publicFundEditorResult;


	}

	/**
	 * dataTables 表单数据返回
	 *
	 * @param request
	 * @return
	 */

	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
	public DataTablePageUtil<PublicFund>  pageDatatables(HttpServletRequest request, PublicFund publicFund) {
//		HttpSession httpSession = request.getSession();
//		User user = (User) httpSession.getAttribute("userInfo");
//		logger.info("用户信息：" + user.toString());
//		int community_id = user.getCommunity().getCommunityId();
//		publicFund.setCommunityId(community_id);

		List<Community> communities =communityMapper.findCommunitys();
		Options os =new Options();
		List<Option> optionList =new ArrayList<>();
		for (Community community : communities) {

			Option option =new Option();
			option.setLabel(community.getCommunityName());
			option.setValue(community.getCommunityId());
			optionList.add(option);


		}
		os.setCommunityId(optionList);
		List<Depart> departs =departMapper.findDeparts();
		optionList =new ArrayList<>();
		for (Depart depart : departs) {

			Option option =new Option();
			option.setLabel(depart.getDepartName());
			option.setValue(depart.getDepartId());
			optionList.add(option);


		}

		os.setDepartId(optionList);



		DataTablePageUtil<PublicFund> dataTable = new DataTablePageUtil<>(request);
		publicFund.setIsDelete(0);
		PageHelper.startPage(dataTable.getPage_num(), 10);
		List<PublicFund> list = publicFundMapper.selectSelective(publicFund);
		PageInfo<PublicFund> pageInfo =new PageInfo<>(list);
		System.out.println(list.size());
		dataTable.setDraw(dataTable.getDraw());
		dataTable.setData(pageInfo.getList());
		dataTable.setOptions(os);
		dataTable.setRecordsTotal((int)pageInfo.getTotal());
		dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
		//返回数据到页面

		return dataTable;

	}

	/**
	 * 通知列表
	 * @param request
	 * @return
	 */
	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = "/publicFundNotify")
	public DataTablePageUtil<Map>  publicFundNotify(HttpServletRequest request) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		String sql = "";

		if (user.getUserTypeId() == 5) {//组织部

			sql = "select p.*,u.real_name,pc.* from tb_public_fund_change pc,tb_user u,tb_public_fund p,tb_community c where   " +
					"u.user_id =p.user_id and pc.pf_id=p.pf_id  and p.community_id = c.community_id " +
					"and pc.is_valid =0 and p.is_delete=0 and pc.current_auditor_id " +
					" in ( SELECT tb_user.user_id FROM tb_user ,tb_public_fund_change " +
					"WHERE  tb_user.user_id=tb_public_fund_change.current_auditor_id and tb_user.user_type_id=4)";

		}else if(user.getUserTypeId() == 3||user.getUserTypeId() == 6||user.getUserTypeId() == 7||user.getUserTypeId() == 8||user.getUserTypeId() == 9) {//领导

			sql = "select p.*,u.real_name,pc.* from tb_public_fund_change pc,tb_user u,tb_public_fund p,tb_community c where   " +
					"u.user_id =pc.current_auditor_id and pc.pf_id=p.pf_id and u.community_id = c.community_id " +
					"and pc.is_valid =0 AND  u.parent_id =" + "'" + user.getUserId() + "'";

		}






		DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
		PageHelper.startPage(dataTable.getPage_num(), 10);
		List<Map> list =		this.getBySqlMapper.findRecords(sql);
		PageInfo<Map> pageInfo =new PageInfo<>(list);
		System.out.println(list.size());
		dataTable.setDraw(dataTable.getDraw());
		for (int i = 0; i < pageInfo.getList().size(); i++) {
			Map map =pageInfo.getList().get(i);
			String d =DateUtil.DATEtoString((Date)map.get("register_time"),"yyyy-MM-dd");
			System.out.println(d);
			map.put("register_time",d);


		}
		dataTable.setData(pageInfo.getList());
		dataTable.setRecordsTotal((int)pageInfo.getTotal());
		dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
		//返回数据到页面

		return dataTable;

	}



	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = "/publicFundOrgNotify")
	public DataTablePageUtil<Map>  publicFundOrgNotify(HttpServletRequest request,Integer isOff) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");

		String sql = "select p.*,c.community_name from tb_public_fund p,tb_community c where   " +
				"p.community_id = c.community_id " +
				" and p.is_delete=0 ";
		if(null!=isOff){
			sql=sql+"  and  p.is_off =" + "'"+isOff+"'";
		}




		DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
		PageHelper.startPage(dataTable.getPage_num(), 10);
		List<Map> list =		this.getBySqlMapper.findRecords(sql);
		PageInfo<Map> pageInfo =new PageInfo<>(list);
		System.out.println(list.size());
		dataTable.setDraw(dataTable.getDraw());
		for (int i = 0; i < pageInfo.getList().size(); i++) {
			Map map =pageInfo.getList().get(i);
			String d =DateUtil.DATEtoString((Date)map.get("register_time"),"yyyy-MM-dd");
			System.out.println(d);
			map.put("register_time",d);


		}
		dataTable.setData(pageInfo.getList());
		dataTable.setRecordsTotal((int)pageInfo.getTotal());
		dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
		//返回数据到页面

		return dataTable;

	}



	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = "/publicFundComNotify")
	public DataTablePageUtil<Map>  publicFundComNotify(HttpServletRequest request,Integer isOff) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");

		String sql = "select p.*,c.community_name from tb_public_fund p,tb_community c where   " +
				"p.community_id = c.community_id " +
				" and p.is_delete=0 AND p.community_id =" + "'"+user.getCommunityId()+"'";
		if(null!=isOff){
			sql=sql+"  and  p.is_off =" + "'"+isOff+"'";
		}




		DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
		PageHelper.startPage(dataTable.getPage_num(), 10);
		List<Map> list =		this.getBySqlMapper.findRecords(sql);
		PageInfo<Map> pageInfo =new PageInfo<>(list);
		System.out.println(list.size());
		dataTable.setDraw(dataTable.getDraw());
		for (int i = 0; i < pageInfo.getList().size(); i++) {
			Map map =pageInfo.getList().get(i);
			String d =DateUtil.DATEtoString((Date)map.get("register_time"),"yyyy-MM-dd");
			System.out.println(d);
			map.put("register_time",d);


		}
		dataTable.setData(pageInfo.getList());
		dataTable.setRecordsTotal((int)pageInfo.getTotal());
		dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
		//返回数据到页面

		return dataTable;

	}




	/**
	 * 审核流程
	 * @param request
	 * @param id
	 * @return
	 */
	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = "/changeDatatables")
	public DataTablePageUtil<Map>  changeDatatables(HttpServletRequest request,@RequestParam  Integer id) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");

		String sql = "select * from tb_public_fund_change,tb_user where tb_public_fund_change.current_auditor_id =tb_user.user_id and  pf_id=" + "'"+id+"'";

		DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
		PageHelper.startPage(dataTable.getPage_num(), 10);
		List<Map> list =		this.getBySqlMapper.findRecords(sql);
		PageInfo<Map> pageInfo =new PageInfo<>(list);
		System.out.println(list.size());
		dataTable.setDraw(dataTable.getDraw());
		dataTable.setData(pageInfo.getList());
		dataTable.setRecordsTotal((int)pageInfo.getTotal());
		dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
		//返回数据到页面

		return dataTable;

	}


	/**
	 * 群众经费审批 是否同意
	 * @param idStr
	 * @param request
	 * @param response
	 * @return
	 */
	@Transactional
	@RequestMapping(method = RequestMethod.PUT, value = "/publicFundEdit")
	public Object publicFundNotifyEdit (@RequestParam("id") String idStr, HttpServletRequest request, HttpServletResponse response) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");

		String[] arr = idStr.split(",");
		EditorResult<Map> publicFundEditorResult = new EditorResult<>();
		List<Map> data =new ArrayList<>();
		PublicFund publicFund =null;

		for (int i = 0; i < arr.length; i++) {
			int publicFundChangeId = Integer.valueOf(arr[i]);
			PublicFundChange publicFundChange =publicFundChangeMapper.selectByPrimaryKey(publicFundChangeId);

			if (null == publicFundChange) {

				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
				return null;
			}
			publicFund =publicFundMapper.selectByPrimaryKey(publicFundChange.getPfId());
			if(publicFund==null){
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
				return null;
			}
			List<FieldError> fieldErrorList = new ArrayList<>();
			String prefix="data[" + publicFundChangeId + "][";
			try {
				int currentState= Integer.valueOf(request.getParameter(prefix + "currentState]"));
				publicFundChange.setIsValid(true); //true代表这条记录的上级领导已经操作
				if(publicFundChangeMapper.updateByPrimaryKey(publicFundChange)>0){
					logger.info("更新群众经费信息成功");
				}else{
					logger.info("更新群众经费日志信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}

				PublicFundChange fc = new PublicFundChange();//产生新的修改日志
				fc.setPfId(publicFund.getPfId());
				fc.setCurrentState(currentState);
				fc.setCurrentAuditorId(user.getUserId());
				fc.setLastAuditorId(publicFundChange.getCurrentAuditorId());
				fc.setLastDatetime(publicFundChange.getCurrentDatetime());
				fc.setCurrentDatetime(new Date());
				fc.setSubmitNumber(publicFundChange.getSubmitNumber());
				fc.setIsValid(true);//直接返回，不再向上级申报

				String sql = "select current_auditor_id  from tb_public_fund_change where pf_id = " +publicFund.getPfId()+" and current_auditor_id !=" +user.getUserId()+"";
				List<Map> back_userIdMaps = this.getBySqlMapper.findRecords(sql);
				if(currentState==3){//建议
					String suggest =request.getParameter(prefix + "suggest]");
					fc.setSuggest(suggest);
					publicFund.setIsOff(3);//

					for (Map back_userIdMap : back_userIdMaps) {
						sql = "insert into tb_back_notify (type_name,project_id,project_name,person_id,flag) values ('publicFund',"+publicFund.getPfId()+",'"+publicFund.getPfTitle()+"',"+back_userIdMap.get("current_auditor_id")+",3)";
						this.getBySqlMapper.insert(sql);

					}






				}else if(currentState==1){//同意 判定用户是否还有领导

					if(user.getUserId()==user.getParentId()){//同意，不存在上级领导
							publicFund.setIsOff(6); //同意完成申报，组织部未查看通知

					}else{//同意，且存在上级领导

						fc.setIsValid(false);//需要等待上级领导处理

					}



				}else if(currentState==2){//拒绝

					publicFund.setIsOff(2);


					for (Map back_userIdMap : back_userIdMaps) {
						sql = "insert into tb_back_notify (type_name,project_id,project_name,person_id,flag) values ('publicFund',"+publicFund.getPfId()+",'"+publicFund.getPfTitle()+"',"+back_userIdMap.get("current_auditor_id")+",2)";
						this.getBySqlMapper.insert(sql);

					}
				}
				if (publicFundMapper.updateByPrimaryKeySelective(publicFund) > 0){
					logger.info("更新群众经费信息成功");
				}else{
					logger.info("更新群众经费信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}
				if(publicFundChangeMapper.insertSelective(fc)>0){
					logger.info("保存群众经费信息成功");
				}else{
					logger.info("保存群众经费信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}



			} catch (NumberFormatException e) {
				logger.error("格式不正确，必须为整形");
				FieldError fieldError =new FieldError("amount","格式不正确，必须为整型");
				fieldErrorList.add(fieldError);
			}
			if(fieldErrorList.size()>0){
				logger.error("字段错误");
				publicFundEditorResult.setFieldErrors(fieldErrorList);
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return publicFundEditorResult;
			}
			String sql="";
			if (user.getUserTypeId() == 5) {

				sql = "select p.*,u.real_name,pc.* from tb_public_fund_change pc,tb_user u,tb_public_fund p,tb_community c where   " +
						"u.user_id =p.user_id and pc.pf_id=p.pf_id  and p.community_id = c.community_id " +
						"and pc.is_valid =0 and p.is_delete=0 AND  pc.pf_change_id =" + "'" + publicFundChangeId + "'";

			}else if(user.getUserTypeId() == 3) {//领导

				sql = "select p.*,u.real_name,pc.* from tb_public_fund_change pc,tb_user u,tb_public_fund p,tb_community c where   " +
						"u.user_id =pc.current_auditor_id and pc.pf_id=p.pf_id and u.community_id = c.community_id " +
						"and pc.is_valid =0 and p.is_delete=0  AND  u.parent_id =" + "'" + user.getUserId()+ "' and pc.pf_change_id =" + "'" + publicFundChangeId + "'";

			}

			List<Map> list =		this.getBySqlMapper.findRecords(sql);
			if(list.size()>0){
				data.add(list.get(0));
			}




		}
		publicFundEditorResult.setData(data);
		return publicFundEditorResult;


	}

	@Transactional
	@RequestMapping(method = RequestMethod.PUT, value = "/publicFundComEdit")
	public Object publicFundComNotifyEdit (@RequestParam("id") String idStr, HttpServletRequest request, HttpServletResponse response) {
		HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");

		String[] arr = idStr.split(",");
		EditorResult<Map> publicFundEditorResult = new EditorResult<>();
		List<Map> data =new ArrayList<>();
		PublicFund publicFund =null;

		for (int i = 0; i < arr.length; i++) {
			int publicFundId = Integer.valueOf(arr[i]);
		
			publicFund =publicFundMapper.selectByPrimaryKey(publicFundId);
			if(publicFund==null){
				response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
				return null;
			}
			List<FieldError> fieldErrorList = new ArrayList<>();
			String prefix="data[" + publicFundId + "][";





			if(null!=request.getParameter(prefix + "is_off]")){
				int is_off =Integer.valueOf(request.getParameter(prefix + "is_off]"));
				publicFund.setIsOff(is_off);



				if (publicFundMapper.updateByPrimaryKeySelective(publicFund) > 0) {
					logger.info("更新项目信息成功");
				} else {
					logger.info("更新项目信息失败");
					response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

				}
			}
			if(fieldErrorList.size()>0){
				logger.error("字段错误");
				publicFundEditorResult.setFieldErrors(fieldErrorList);
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return publicFundEditorResult;
			}
			String sql = "select p.*,c.community_name from tb_public_fund p,tb_community c where   " +
					"p.community_id = c.community_id " +
					" and p.is_delete=0  "+
					" and p.pf_id =" + "'"+publicFundId+"'";
			List<Map> list =		this.getBySqlMapper.findRecords(sql);
			if(list.size()>0){
				data.add(list.get(0));
			}




		}
		publicFundEditorResult.setData(data);
		return publicFundEditorResult;


	}

	
	
	
	private void getPublicFund(HttpServletRequest request, String prefix, PublicFund publicFund,List<FieldError> fieldErrorList ) {
		if (null!=request.getParameter(prefix + "communityId]")&&!request.getParameter(prefix + "communityId]").isEmpty()) {
			publicFund.setCommunityId(Integer.valueOf(request.getParameter(prefix + "communityId]")));


		}
		if (null!=request.getParameter(prefix + "departId]")&&!request.getParameter(prefix + "departId]").isEmpty()) {
			publicFund.setDepartId(Integer.valueOf(request.getParameter(prefix + "departId]")));


		}

//		publicFund.setPpName(request.getParameter(prefix + "ppName]"));
//		publicFund.setPpAdd(request.getParameter(prefix + "ppAdd]"));
//		publicFund.setPpDetail(request.getParameter(prefix + "ppDetail]"));
//		publicFund.setPeople(request.getParameter(prefix + "people]"));
//		try {
//			publicFund.setPpDate(DateUtil.StrToDate1(request.getParameter(prefix + "ppDate]")));
//		} catch (NumberFormatException e) {
//			logger.error("时间格式不正确，必须为YYYY-MM-DD");
//			FieldError fieldError =new FieldError("amount","时间格式不正确，必须为YYYY-MM-DD");
//			fieldErrorList.add(fieldError);
//		}
//		try {
//			publicFund.setAmount(Double.valueOf(request.getParameter(prefix + "amount]")));
//		} catch (NumberFormatException e) {
//			logger.error("格式不正确，必须为Double型");
//			FieldError fieldError =new FieldError("amount","格式不正确，必须为Double型");
//			fieldErrorList.add(fieldError);
//		}
//		publicFund.setEventsOrg(request.getParameter(prefix + "eventsOrg]"));
//		publicFund.setBudger(request.getParameter(prefix + "budger]"));
//
//
//		if (null != request.getParameter(prefix + "isOff]")&&!request.getParameter(prefix + "isOff]").isEmpty()) {
//			try {
//				publicFund.setIsOff(Integer.valueOf(request.getParameter(prefix + "isOff]")));
//			} catch (NumberFormatException e) {
//				logger.error("数量格式不正确，必须为整形数字");
//				FieldError fieldError = new FieldError("isOff", "格式不正确，必须为整形数字");
//				fieldErrorList.add(fieldError);
//			}
//
//		}
//		if (null != request.getParameter(prefix + "isDelete]")&&!request.getParameter(prefix + "isDelete]").isEmpty()) {
//			try {
//				int isDelete = Integer.valueOf(request.getParameter(prefix + "isDelete]"));
//				publicFund.setIsDelete(isDelete);
//			} catch (NumberFormatException e) {
//				logger.error("数量格式不正确，必须为整形数字");
//				FieldError fieldError = new FieldError("isDelete", "格式不正确，必须为整形数字");
//				fieldErrorList.add(fieldError);
//			}
//
//		}
//		if (null != request.getParameter(prefix + "submitNumber]")&&!request.getParameter(prefix + "isDelete]").isEmpty()) {
//			try {
//				publicFund.setSubmitNumber(Integer.valueOf(request.getParameter(prefix + "submitNumber]")));
//			} catch (NumberFormatException e) {
//				logger.error("数量格式不正确，必须为整形数字");
//				FieldError fieldError = new FieldError("submitNumber", "格式不正确，必须为整形数字");
//				fieldErrorList.add(fieldError);
//			}
//
//		}


	}







}
